package org.framework.lazy.cloud.network.heartbeat.protocol.socket5;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.socksx.v5.Socks5CommandRequestDecoder;
import io.netty.handler.codec.socksx.v5.Socks5InitialRequestDecoder;
import io.netty.handler.codec.socksx.v5.Socks5ServerEncoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Socks5ProxyServer {
    private final int port;

    public Socks5ProxyServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        new Socks5ProxyServer(1080).run();
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {

                            //socks5响应最后一个encode
                            ch.pipeline().addLast(Socks5ServerEncoder.DEFAULT);
                            // 初始化连接
                            ch.pipeline().addLast(new Socks5InitialRequestDecoder());
                            ch.pipeline().addLast(new Socks5InitialRequestHandler());


                            // 认证
//                            ch.pipeline().addLast(new Socks5PasswordAuthRequestDecoder());
//                            ch.pipeline().addLast(new Socks5PasswordAuthRequestInboundHandler());

                            // 连接请求
                            ch.pipeline().addLast(new Socks5CommandRequestDecoder());
                            ch.pipeline().addLast(new Socks5CommandRequestHandler(group));
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 512)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000)
            ;

            log.info("启动 socket:{}", port);
            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();

        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}    